package elephant.rpc.network.netty;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import elephant.rpc.client.core.NetworkService;
import elephant.rpc.server.message.RPCMessage;
import elephant.rpc.server.session.RPCSession;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 
 * @author skydu
 *
 */
@Sharable
public class NettyClientHandler extends SimpleChannelInboundHandler<RPCMessage> {

	private static final Logger logger = LoggerFactory.getLogger(NettyClientHandler.class);
	//
	private NetworkService networkService;

	//
	public NettyClientHandler(NetworkService networkService) {
		super();
		this.networkService = networkService;
	}

	//
	@Override
	public void channelActive(ChannelHandlerContext ctx) {
		if (logger.isDebugEnabled()) {
			logger.debug("RPCClientHandler channelActive");
		}
	}

	//
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("channelInactive rpc session sessionDisconnected:{}", ctx.channel());
		}
	}
	//

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		if (logger.isWarnEnabled()) {
			logger.warn("RPCClientHandler Unexpected exception from downstream.", cause);
		}
		ctx.close();
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, RPCMessage msg) throws Exception {
		RPCSession session = ctx.channel().attr(RPCSession.SESSION_KEY).get();
		networkService.onMessageReceived(session,msg);
	}
}
